package com.p.lib.common.http;

import com.google.gson.Gson;
import com.p.lib.app.BaseApplication;
import com.p.lib.util.MD5;

import java.io.File;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2018/5/31 0031.
 */

public class PostParam {

    private static final String REQ_KEY = "qowienfqwk92834pjmd0239487899055j#^%$DFSs"; //公用Key

    private TreeMap<String, Object> tm = new TreeMap<>();

    private FormBody.Builder builder = new FormBody.Builder();

    public static PostParam build(){

        return new PostParam()
                .add("langtype", BaseApplication.isEnglish()?"1":"0")
                .add("logintoken", BaseApplication.LOGIN_TOKEN)
                .add("backparm", 0);
    }


    public PostParam add(String key, Object value){

        tm.put(key, value);
        builder.add(key, String.valueOf(value));

        return this;
    }

    /**
     * 获取get请求参数
     * @return
     */
    public TreeMap<String, Object> getParams(){
        return tm;
    }

    /**
     * 获取Post请求参数
     * @return
     */
    public FormBody getPostParams(){

        return builder.build();
    }

    /**
     * 获取value
     * @param key
     * @return
     */
    public String getValue(String key){
        return String.valueOf(tm.get(key));
    }

    /**
     * 获取Post请求参数
     * @return
     */
    public RequestBody getPostParamsJson(){
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),  new Gson().toJson(tm));
        return requestBody;
    }


    public TreeMap<String, Object> getParamsAddKey() {

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : tm.entrySet()) {

            sb.append(entry.getValue()+"#");

        }
        sb.append(REQ_KEY);
        tm.put("key", MD5.getMD5(sb.toString()).toLowerCase());

        return tm;
    }


    public RequestBody getPostParamsAddKey(){
        StringBuffer sb = new StringBuffer();

        for (Map.Entry<String, Object> entry : tm.entrySet()) {

            sb.append(entry.getValue()+"#");

        }
        sb.append(REQ_KEY);

        builder.add("key", MD5.getMD5(sb.toString()).toLowerCase());

        return builder.build();

    }


}
